'use strict';

const Controller = require('egg').Controller;
const jwt = require('jsonwebtoken');

class UserController extends Controller {
    //注册
    async registry() {
        let {ctx,service} = this;
        let role_id = 1;
        let role_name = '学生';
        let {username,password,num} = ctx.request.body;
        //1.容错
        if(username && /^\w{4,6}$/.test(password) && num){
            //2.排重
            let target = await service.user.selectUser(num);
            if(target.length){
                //学号已经使用
                ctx.body = {
                    code:3,
                    msg:'此学号已被使用'
                }
            }else{
                //3.注册
                try{
                    let hmcPwd = ctx.helper.hmc(password);
                    await service.user.registry(username,hmcPwd,num,role_id,role_name);
                    ctx.body = {
                        code:1,
                        msg:'注册成功'
                    }
                }catch(e){
                    ctx.body = {
                        code:0,
                        msg:e
                    }
                }
            }
        }else{
            ctx.body = {
                code:2,
                msg:'参数有误'
            }
        }
    }
    //登录
    async login(){
        let {ctx,service}  = this;
        let {num,password} = ctx.request.body;
        //1.容错处理
        if(/^\w{4,6}$/.test(password) && num){
            //2.查询是否有学号和密码一致的数据
            let hmcPwd = ctx.helper.hmc(password);
            let list = await service.user.login(num,hmcPwd);
            console.log(list);

            if(list.length){
                let {username,role_name,role_id} = list[0];
                let token = jwt.sign({role_id},'score',{expiresIn:60*60});
                ctx.body = {
                    code:1,
                    msg:'登录成功',
                    username,
                    role_name,
                    role_id,
                    token
                }
            }else{
                ctx.body = {
                    code:0,
                    msg:'登录失败'
                }
            }
        }else{
            ctx.body = {
                code:2,
                msg:'参数有误'
            }
        }
    }
}

module.exports = UserController;
